﻿
#include <iostream>
#include "../include/Game.h"
#include "../include/Board.h"
#include "../include/Computer.h"
#include <vector>

using namespace std;


Game::Game()
{
	board.clear();
}

//play主函数
void Game::playConsole()
{
	//初始化
	board.clear();
	Computer computer;
	bool flag = true;
	int current = 1;
	int x = -1, y = -1;
	vector<int> v;

	//设置玩家的下棋
	board.setPlayerSymbol('X');
	board.setComputerSymbol('O');
	cout << "You play as " << board.getPlayerSymbol() << ". Let's start!" << endl;

	current = 1;
	cout << ". You go first!" << endl;

	board.print();
	while (flag)
	{
		cout << endl;
		if (current == 1)
		{ // 玩家下棋
			cout << "Your turn. (" << getCurrentSymbol(current) << " )" << endl;
			cout << "Enter X coordinate of your move: ";
			cin >> x;
			cout << "Enter Y coordinate of your move: ";
			cin >> y;
		}
		else
		{ // AI下棋

			v = computer.nextMoveAlphaBeta(board);
			x = v[0];
			y = v[1];
		}

		// 检查合法
		if (!board.checkEmpty(x, y))
		{
			cout << endl
				 << "Not a legal move. Try again!" << endl;
			cout << "x,y:" << x << " " << y << endl;
			continue; 
		}
		else
		{ // 合法更新棋盘

			board.setValue(x, y, getCurrentSymbol(current));
			board.print();
			if (current == 1)
			{
				cout << "Your move is : (" << x << ", " << y << ") " << endl;
			}
			else
			{
				cout << "My move is : (" << x << ", " << y << ") " << endl;
			}
		}

		// 判断胜利
		if (board.win(x, y))
		{
			board.print();
			if (current == 1)
			{
				cout << "CONGRATULATIONS! YOU WON!" << endl;
			}
			else
			{
				cout << "I WON!!!" << endl;
			}
			break;
		}
		else if (board.draw())
		{
			board.print();
			cout << "Draw game!" << endl;
			break;
		}
		else
		{ // 切换角色
			current = 3 - current;
		}
	}
}

//当前玩家
char Game::getCurrentSymbol(int current)
{
	if (current == 1)
	{
		return board.getPlayerSymbol();
	}
	else
	{
		return board.getComputerSymbol();
	}
}

//开始游戏
void Game::run()
{
	bool flag = true;
	char x;
	while (flag)
	{
		playConsole();
		cout << "Do you want to play another game? y/n" << endl;
		cin >> x;
		if (x == 'N' || x == 'n')
		{
			flag = false;
		}
		else
		{
			cout << "------------------------------------------------------" << endl;
		}
	}
}
